/*
 * @Author: Kang
 * @Date: 2022-06-26 17:19:25
 * @Last Modified by: Kang
 * @LastEditTime: 2022-07-01 15:05:18
 */
'use strict';
module.exports = (options, app) => {
  return async function (ctx, next) {
    //拿到不需要验证的token的路由
    const routerAuth = [ //白名单
      "login",
      "front"
    ];
    //获取当前路由
    const url = ctx.url;

    var strs = new Array(); //定义一数组
    strs = url.split("/"); //字符分割
    console.log('strs', strs[1], routerAuth.includes(strs[1]), routerAuth.includes(strs[2] ? strs[1] : strs[2]))
    //判断当前路由是否需要验证token
    const flag = routerAuth.includes(strs[2] ? strs[1] : strs[2])    //根据模块来判定白名单
    console.log('flag', flag)
    // const flag = routerAuth.includes(url)    //根据模块来判定白名单
    if (flag) {
      await next();
    } else {
      //获取token,如果没有传入token，则为空
      // console.log(ctx.headers, "获取请求头")
      var token = ctx.headers.token ? ctx.headers.token : '';
      // var token = ctx.headers.authorization ? ctx.headers.authorization : '';  //请求头字段为 authorization时使用
      // token = token.substring(7) //把Bearer 截取掉，解析的时候不需要加上Bearer 
      console.log(token, "获取thonk")
      // 解析token
      try {
        console.log(token, app.config.jwt.secret)
        const decode = await app.jwt.verify(token, app.config.jwt.secret);
        ctx.user = {
          username: ctx.csrf.username,
          password: ctx.csrf.password,
          user_id: 1
        };

        if (!decode.username) {
          ctx.body = {
            code: 401,
            message: '该用户已被停用',
            data: null
          }
        } else {

          await next();
        }

      } catch (err) {
        console.log(err)
        app.logger.debug(err); //打印错误日志
        ctx.body = {
          code: 401,
          message: 'token失效或解析错误',
          data: null
        }
      }

    }

  }
}